package com.pinhuba.bams.framework.controller;

import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.os.AsyncTask;
import com.pinhuba.bams.framework.ErrorCode;
import com.pinhuba.bams.framework.UrlType;
import com.pinhuba.bams.framework.exception.AirPlaneModeException;
import com.pinhuba.bams.framework.exception.NetworkException;
import com.pinhuba.bams.framework.exception.NoInternetException;
import com.pinhuba.bams.framework.exception.TimeoutException;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.PhoneStateUtil;

public class AsynCommon extends AsyncTask<UrlType, Void, String> {

	protected HashMap<String, String> params;
	protected UrlType urlType;
	protected Activity context;
	protected ErrorListener errorListener;
	protected ErrorCode errorCode;

	public AsynCommon(Activity context, ErrorListener errorlistener, HashMap<String, String> params) {
		this.errorCode = ErrorCode.SUCCESS;
		this.context = context;
		this.errorListener = errorlistener;
		this.params = params;
	}

	@Override
	protected String doInBackground(UrlType... urlTypes) {
		String rst = null;
		try {
			if (this.context == null) {
				PhoneStateUtil.checkNetWork();
			} else {
				PhoneStateUtil.checkNetWork(context);
			}
		} catch (AirPlaneModeException e) {
			e.printStackTrace();
			errorCode = ErrorCode.AIRPLANE_MODE;
		} catch (NoInternetException e) {
			e.printStackTrace();
			Loger.d("The no intent");
			errorCode = ErrorCode.NO_INTERNET;
		}
		if (errorCode != ErrorCode.SUCCESS)
			return null;

		urlType = urlTypes[0];

		try {
			rst = doExecRequest(urlType, params);
		} catch (TimeoutException e) {
			errorCode = ErrorCode.READW_TIMOUT;
		} catch (NetworkException e) {
			e.printStackTrace();
			errorCode = ErrorCode.NO_INTERNET;
		} catch (IOException e) {
			e.printStackTrace();
			errorCode = ErrorCode.INVALID_IO;
		}
		return rst;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (errorCode == ErrorCode.SUCCESS) {
			if (errorListener != null) {
				errorListener.onSuccess(this.urlType, result);
			}
		} else {
			if (errorListener != null) {
				errorListener.onError(this.urlType, errorCode);
			}
		}
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
	}

	/**
	 * 执行请求
	 * 
	 * @param type
	 * @param params
	 * @return
	 * @throws TimeoutException
	 * @throws NetworkException
	 * @throws IOException
	 */
	private String doExecRequest(UrlType type, HashMap<String, String> params) throws TimeoutException, NetworkException, IOException {
		String rst = null;
		try {
			rst = Handler.doGet(type, params);
		} catch (TimeoutException e) {
			throw new TimeoutException();
		} catch (NetworkException e) {
			throw new NetworkException();
		}
		return rst;
	}
}
